var online_stat_time;
var xhr_frndlst;
var xhr_frndlst_running = 0; 
var just_posted = 0; // to detect if a post was just made by the user in which case the stream will be moved to his level
var image_rotate;
var image_rotate_angle = 0;
var polling_timeout;
var gp_xhr;


$(function() {
	// poll only when the the user is logged in and hence this id will be set
	if($('#loggedin_userid').length>0) 
		online_stat_time = setTimeout("online_stat()", 30000);
	
	$('#header_gausipp_menu').click(function() {
		//$('#gausipp_menu').toggle();
		if($('#gausipp_menu').is(':visible'))
			{
				$('#gausipp_menu').hide();
				if(!$(this).hasClass('header-menu-active')) 
				 	$(this).removeClass('blackbg');
			}
			
		else
		{
			if(!$(this).hasClass('header-menu-active')) 
				 	$(this).addClass('blackbg');
			$('#gausipp_menu').show();
		} 
			
	});
	
	$('#header_chat_link').click(function() {
		//$('#gausipp_menu').toggle();
		if($('#header_chat_menu').is(':visible'))
			{
				$('#header_chat_menu').hide();
				if(!$(this).hasClass('header-menu-active')) 
				 	$(this).removeClass('blackbg');
			}
			
		else
		{
			if(!$(this).hasClass('header-menu-active')) 
				 	$(this).addClass('blackbg');
			$('#header_chat_menu').show();
			refresh_unread();
		} 
			
	});
	
	// for hiding the menu when clicjed outside
	$(document).click(function(event) {
		// hiding the comment box
		/*
 		if($(event.target).parents().index($('.commentbox')) == -1 && $(event.target).parents().index($('.open_commentbox')) == -1)
			{ 
				alert($(event.target).parents().index($('.open_commentbox')));
				$('.commentbox').slideUp();
			} 
		 */
		 //hiding the gausipp menu
    if($(event.target).parents().index($('#gausipp_menu')) == -1 && $(event.target).parents().index($('#header_gausipp_menu')) == -1)
     {
        if($('#gausipp_menu').is(":visible")) {
            $('#gausipp_menu').hide();
         if(!$('#header_gausipp_menu').hasClass('header-menu-active'))
         	$('#header_gausipp_menu').removeClass('blackbg');
        }
    }   
    
    if($(event.target).parents().index($('#header_chat_menu')) == -1 && $(event.target).parents().index($('#header_chat_link')) == -1)
     {
        if($('#header_chat_menu').is(":visible")) {
            $('#header_chat_menu').hide();
         if(!$('#header_chat_link').hasClass('header-menu-active'))
         	$('#header_chat_link').removeClass('blackbg');
        }
    }   
	
	 if($('#gp_frnd_list').length>0 && $(event.target).parents().index($('#gp_frnd_list')) == -1)
     {
        if($('#gp_frnd_list').is(":visible")) {
            $('#gp_frnd_list').hide(); 
			$('#gp_frnd_list .gp_frnd_list_wrapper').removeClass('gp_frnd_list_highlight');        
        }
    }
	
	if($('.leftcol_filterfriendsListSuggestions').length>0 && $(event.target).parents().index($('.leftcol_filterfriendsListSuggestions')) == -1)
     {
            $('.leftcol_filterfriendsListSuggestions').hide(); 			
	}

		
         
	});
	
	
	$(window).keydown(function(e){
		var key = e.which;
		
		if(( key== 38 || key==40 || key==13 ) && ($('#gp_frnd_list:visible').length > 0) )
		{
			var ele = $('#gp_frnd_list .gp_frnd_list_wrapper.gp_frnd_list_highlight:visible');
			var num = $('#gp_frnd_list .gp_frnd_list_wrapper:visible').length;
			//alert(ele.length);
			if(key == 40)
			{
			if(ele.length > 0)
			{					
				var index = $('#gp_frnd_list .gp_frnd_list_wrapper:visible').index(ele);	
				if(index == num-1) { $('#gp_frnd_list .gp_frnd_list_wrapper:visible').removeClass('gp_frnd_list_highlight'); return; }
				var next = $('#gp_frnd_list .gp_frnd_list_wrapper:visible').eq(index+1);				
				//alert(next.length);
				ele.removeClass('gp_frnd_list_highlight');
				next.addClass('gp_frnd_list_highlight');
				//alert("here");
				
			}
			else
			{
				$('#gp_frnd_list .gp_frnd_list_wrapper:visible:first').addClass('gp_frnd_list_highlight');
			}
			}
			else if(key == 38)
			{
				if(ele.length > 0)
				{					
					var index = $('#gp_frnd_list .gp_frnd_list_wrapper:visible').index(ele);
					if(index == 0) { $('#gp_frnd_list .gp_frnd_list_wrapper:visible').removeClass('gp_frnd_list_highlight'); return; }
					var next = $('#gp_frnd_list .gp_frnd_list_wrapper:visible').eq(index-1);				
					//alert(next.length);
					ele.removeClass('gp_frnd_list_highlight');
					next.addClass('gp_frnd_list_highlight');
					//alert("here");				
				}
			}
			else if(key == 13)
			{
				if(ele.length > 0)
				{					
					ele.find('input[type=checkbox]').click();
				}
			}
			
		}
		
		 
		if(( key== 38 || key==40 || key==13 || key==27) && ($('.leftcol_filterfriendsListSuggestions').length > 0) )
		{
			var ele = $('.leftcol_filterfriendsListSuggestions').find('div.gp_frnd_list_highlight');
			var content = $('.leftcol_filterfriendsListSuggestions').find('div');
			if( key == 40)
			{
				if(ele.length > 0)
				{
					content.removeClass('gp_frnd_list_highlight');
					var index = content.index(ele);
					if(index == content.length-1) // reached the end
						content.eq(0).addClass('gp_frnd_list_highlight');
					else
						content.eq(index+1).addClass('gp_frnd_list_highlight');
				}
				else 
				content.eq(0).addClass('gp_frnd_list_highlight');				
			}
			else if(key == 38)
			{
				if(ele.length > 0)
				{
					content.removeClass('gp_frnd_list_highlight');
					var index = content.index(ele);
					if(index == 0) // reached the end
						content.eq(content.length -1).addClass('gp_frnd_list_highlight');					
					else
						content.eq(index-1).addClass('gp_frnd_list_highlight');
				}
				else content.eq(content.length -1).addClass('gp_frnd_list_highlight');					
			}
			else if(key == 13)
			{
				ele.click();
			}
			else if(key == 27)
			{
				$('.leftcol_filterfriendsListSuggestions').remove();
			}
		}
		 
	});

	
});

function online_stat() {

	
	//alert("conn");
	var checklist = "";
	// for updating the online status of people
	$('.online_stat').each(function() {
		checklist += $(this).attr('id') + ";";
	});
	
	// for updating the unread part of 
	$('.unread_stat').each(function() {
		checklist += $(this).attr('id') + ";";
	});

	// for updating time stamps
	$('.time_stream').each(function() {
		checklist += $(this).attr('id') + ";";
	});
	
	
	
	// to check for new comments
	// although not needed right now, but still keep it
	/*
	$('.comments_new').each(function() {
		var id = $(this).attr('id');
		var user = $('#loggedin_userid').text();
		init_comments(user, id);
	});
	*/
	//alert(checklist);

	$.ajax({
		type : "POST",
		url : "php/online_stat.php",
		async : true,
		data : "checklist=" + checklist,
		success : function(data) {
			var json = jQuery.parseJSON(data);
			if(json['session'] == "true") {//alert("still logged in");
			} else {
				alert("You are not logged in");
				window.location = "index.php";
			}

			//if(json["error"]!="" && json["error"]!= NULL)
			//	alert("yo: "+json["error"]);

			var num = $('.online_stat').length;
			var len = 0;
			//for(var k in json) if(json.hasOwnProperty(k)) len++;
			//if(len == num+1 && num!=0){
			$('.online_stat').each(function() {
				var id = $(this).attr('id');
				$(this).html(json['' + id + '']);
				//alert(json[''+id+'']);
			});
			$('.unread_stat').each(function() {
				var id = $(this).attr('id');
				$(this).html(json['' + id + '']);
				//alert(json[''+id+'']);
			});
			$('.time_stream').each(function() {
				var id = $(this).attr('id');
				$(this).html(json['' + id + '']);
				//alert(json[''+id+'']);
			});
			//}

			online_stat_time = setTimeout("online_stat()", 30000);
		},
		error : function(XMLHttpRequest, textStatus, errorThrown) {
			if(errorThrown != "")
				show_msg('<span class="poll_err">ping error: ' + errorThrown + ' <span class="a" onclick=\'window.location.reload();\'>refresh</span><br></span>', "perm");
			online_stat_time = setTimeout("online_stat()", 5000);
		},
	});
}



function init_gp_polling(user, type, timestamp)
{ 
	show_msg("poll_err","hide");
	
	var string;
	if(timestamp == undefined)
		timestamp = "";	
	
	$('#stream_realtime_status').html('offline - please <span class="a" onclick=\'$("#leftColumnRefreshLink").click();\'>refresh</span> the page');
	gp_xhr = $.ajax({
		type: "POST",
		url: "php/ajax/group/poll.php", 
		async: true,
		data: "user="+user+"&type="+type+"&timestamp="+timestamp,
		success: function(data) {
			$('#stream_realtime_status').text("checking.");
			var json = eval('('+data+')');
			//if(json['output'] != "") alert(json['output']);			 
					
			if(json["new"] == "true")				 
				 {
				 	$('#stream_realtime_status').text("fetching new stuff");
				 // for checking for new posts in the stream
					$('.stream_new').each(function() {
						var id = $(this).attr('id');
						var user = $('#loggedin_userid').text();
						init_stream(user, id);
					});					
					// then run this function again without giving it any timestamp so that it calculates one by itself					
				 }
				 
				var temp = json['time'];
				polling_timeout = setTimeout(
				'init_gp_polling("'+user+'", "'+type+'", "'+temp+'")', /* Try again after.. */
				"200"); /* milliseconds (1 second) */			
		},
		 error: function(XMLHttpRequest, textStatus, errorThrown){
		 	$('#stream_realtime_status').html('offline - please <span class="a" onclick=\'$("#leftColumnRefreshLink").click();\'>refresh</span> the page');
		 	
			//alert(type+" failure " + textStatus);
		 		if(textStatus!="abort" && textStatus!="error")
					show_msg('<span class="poll_err">Oh snap! There was an error polling the server. code:'+textStatus+' <span class="a" onclick=\'window.location.reload();\'>refresh</span><br></span>',"perm");
                /*polling_timeout = setTimeout(
                    'init_gp_polling("'+user+'", "'+type+'", "'+timestamp+'")', "5000"); /*  try again after milliseconds (5seconds) */
					
            },
		 
	});
	$('#stream_realtime_status').text("online");
}


function filter_frndlst(val) {
	//var val = $(element).val();

	//var val = $(ele).parent().find('input[type=text]').val();
	if(val == "") {
		$('#gp_frnd_list').hide();
		//$('#gp_frnd_list').find('span.frndlst_name').parent().parent().hide();
		return;
	}
	else
		$('#gp_frnd_list').show();

	// number of total friends
	//$(ele).val('filtering');
	val = val.toLowerCase();
	//$('#gp_frnd_list').find('span.frndlst_item').show();

	//$(ele).attr('disabled',true);
	var count = 0;
	
	$('#gp_frnd_list').find('span.frndlst_name').parent().parent().parent().hide();
	$('#gp_frnd_list').find('span.frndlst_name').each(function() {
		var name = $(this).text();
		name = name.toLowerCase();
		if(name.indexOf(val) != -1)			
			{$(this).parent().parent().parent().show(); count++;}
		if(count == 5) return false;
	});
	//update_gp_frnd_list_count();
	//$(ele).attr('disabled',false);
	//$(ele).val('filter');
}


function filter_frndlst2(ele, e) {

	var key = e.which;
	
	if(key == 38 || key == 37 || key == 39 || key == 40 || key==27)
		return;
	
	var val = $(ele).val();
	var id = $(ele).attr('id');
	var arr = id.split("_");
	var type = arr[0]+"_"+arr[1];
	
	if(val == "")
		{
		$('#'+type+'_friendsListSuggestions').html('');
		return;
		}
	
	if(xhr_frndlst_running == 1)
		xhr_frndlst.abort();
	else 
		xhr_frndlst_running == 1;
	
	xhr_frndlst = $.ajax({
            type: "POST",
            url: "php/ajax/group/suggestFriends.php",
            data: "val="+val+"&type="+type,
            success: function(msg) {
                    $('#'+type+'_friendsListSuggestions').html('<div style="position:absolute;background:#fff;border:1px solid #aaa;z-index:10;max-height:200px;overflow:auto;width:200px" class="leftcol_filterfriendsListSuggestions" >'+msg+'</div>');
					xhr_frndlst_running == 0;
                }
        });
		
}

function add_more_members(ele)
{
	
	var string = $(ele).attr('name');
	if(!confirm("Are you sure, you want to add "+$(ele).text()+" in this circle?"))
		return;
	var name = $(ele).text();
	var arr = string.split("_");
	var type = arr[0]+"_"+arr[1];
	var id = arr[2];
	$('#'+type+'_friendsListSuggestions').html('');
	$.ajax({
            type: "POST",
            url: "php/ajax/group/add_members.php",
            data: "gp_mem="+id+":"+name+";"+"&gpid="+arr[1],
            success: function(msg) {	
					if(msg!="") { alert(msg); return; }
					$.ajax({
						type : "POST",
						url : "php/sidebar/group_sidebar.php",
						async : true,
						data : "gpid=" + arr[1],
						success : function(data) {	
							$('#group_'+arr[1]+'_friendsList').html(data);				
						}
					});
                    //reload the list
                }
        });	
}


function frndlst_click() {
	var count = 0;
	var temp = "";
	$('#gp_frnd_list_sel').find('span').remove();
	$('#gp_frnd_list_sel_id').text("");
	$('#gp_frnd_list').hide(); // hiding the suggestions
	$('#gp_frnd_list .gp_frnd_list_wrapper').removeClass('gp_frnd_list_highlight');
	
	$('#gp_frnd_list').find('input[type=checkbox]').each(function() {
		if($(this).attr('checked')) {
			$(this).parent().find('div').addClass('frndlst_item_sel');
			var id = $(this).attr('id');
			var name = $('#' + id + '_name').text();
			//adding the id in the hidden span and the name in the div for the user to see
			$('#gp_frnd_list_sel_id').append(id + ':' + name + ';');
			temp = temp + '<span style="display:inline-block;background:#fee;padding:2px;border-radius:3px;margin:2px;border:1px solid #ddd"><span><img src="images/cross.png" class="cross-image" onclick=\'$("#'+id+'").click();\'></span>&nbsp;<span>'+name+"</span></span> ";
			count++;
		}
		else $(this).parent().find('div').removeClass('frndlst_item_sel');
	});
	$('#gp_frnd_list_sel').html(temp+$('#gp_frnd_list_sel').html());
	$('#gp_frnd_list_sel').find('input[type=text]').focus();
	
}

/*
 // was earlier used to show the number of frnds in the list

 function update_gp_frnd_list_count(type)
 {
 if( type == "all")
 $('#gp_frnd_list').find('span.frndlst_name').parent().parent().show();

 var length = $('#gp_frnd_list').find('span.frndlst_name').parent().parent().length;

 var counter = 0; // to count the number of friends being displayed
 $('#gp_frnd_list').find('span.frndlst_name').each(function() {
 if($(this).parent().parent().is(":visible"))
 counter++;
 });
 //alert(counter);
 $('div#gp_frnd_list_count').text(counter);
 if(length!=counter)
 $('div#gp_frnd_list_show_all').show();
 else
 $('div#gp_frnd_list_show_all').hide();

 }

 */

function submit_gp_form() {
	//alert("here");
	
	var err = "";
	//if(!$('#agreeornot').attr('checked'))
	//	err += "You need to abide by the rules<br>";
	
	var user = $('#loggedin_userid').text();
	var username = $('#loggedin_username').text();
	
	var gp_mem = $('#gp_frnd_list_sel_id').text();
	if(gp_mem == "")
		err += "You haven't selected any friend<br>";

	var gp_name = $('#gp_name').val();
	if(gp_name.length > 50)
		err += "The circle name must be less than 50 characters<br>";

	//if(!isalphanumeric(gp_name))
	//	err += "Circle name can contain alphabets, numbers and underscore only. No spaces<br>";
	

	var gp_description = $('#gp_description').val();
	if(gp_description.length > 500)
		err += "Circle description should be less than 500 characters. <br>";

	var gp_visibility = $('#gp_visibility').val();
	if(gp_visibility == "")
		err += "You haven't selected any visibility criteria<br>";
		
	if(err != "") {
		$('#gp_err_msg').html(err).slideDown();
		return
	} else {
		//
		$('#gp_err_msg').html("").fadeOut();
		$('#gp_form_submit_button').attr('disabled', true).css('opacity','0.5').val("Saving")
		$.post(
			"php/ajax/submit_gp_form.php",
			{gp_mem: gp_mem, gp_name: gp_name, gp_visibility: gp_visibility, user: user, user_name: username, gp_description: gp_description },
			function(msg) {
				var temp = new Array();
				temp = msg.split('_');
				if(temp[0] == "id") {
					window.location = "index.php?cat=group&action=gausipp&gpid=" + temp[1];
				} else {
					show_msg('<span class="submit_gp_form_msg">'+msg+'</span>', "perm");
					$('#gp_form_submit_button').attr('disabled', false).css('opacity','1').val("Go");
				}
			});
	}
}

function show_msg(msg, type) {
	//alert(msg+type);

	if(type == "perm") {
		if(!$('#show_msg_msg').is(":visible"))// slide down only if its not visible
			$('#show_msg_msg').show();
		$('#show_msg_msg').append(msg);
	} else if(type == "alert") {
		if(!$('#show_msg_msg').is(":visible"))// slide down only if its not visible
				$('#show_msg_msg').show();
		var classs = $(msg).attr('class');
		
		$('#show_msg_msg').append(msg);
		setTimeout(function(){
			$('#show_msg_msg').find('.'+classs+'').remove();
			if($('#show_msg_msg').html() == "")
					$('#show_msg_msg').hide();
		}, 4000 );

		
	} else if(type == "hide") {
		if(msg == "")
			{
				$('#show_msg_msg').html("");
				$('#show_msg_msg').hide();
				//$('#show_msg_msg').animate({top:'-70px'},500);
			}
		else
			$('#show_msg_msg').find('.' + msg + '').remove();
		if($('#show_msg_msg').html() == "")
			$('#show_msg_msg').hide();
			//$('#show_msg_msg').animate({top:'-70px'},500);
	}

}

function isalphanumeric(checkString) {
	var regExp = /^[A-Za-z0-9]$/;
	if(checkString != null && checkString != "") {
		for(var i = 0; i < checkString.length; i++) {
			// alphanumeric characters and underscore allowed
			if(!checkString.charAt(i).match(regExp) && checkString.charAt(i) != "_") {
				return false;
			}
		}
	} else {
		return false;
	}

	return true;
}

function strpos(haystack, needle, offset) {
	// Finds position of first occurrence of a string within another
	//
	// version: 1109.2015
	// discuss at: http://phpjs.org/functions/strpos
	// +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +   improved by: Onno Marsman
	// +   bugfixed by: Daniel Esteban
	// +   improved by: Brett Zamir (http://brett-zamir.me)
	// *     example 1: strpos('Kevin van Zonneveld', 'e', 5);
	// *     returns 1: 14
	var i = (haystack + '').indexOf(needle, (offset || 0));
	return i === -1 ? false : i;
}

///////////////////////////////////////////////////////    POSTS  ///////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function submit_postbox(user, ele, type) {
	var temp1 = new Array();
	temp1 = type.split("_");
	if(temp1[0] != "pms") {
		var val = $('#post_box_' + type + '').html();		
		//var val1 = $('#post_box_' + type + '').text();
		val = val.replace(/<div><br><\/div>/, '');
		val = val.replace(/<div>/, '[br]');
		val = val.replace(/<\/div>/, '');
		val = val.replace(/&nbsp;/g, '');
		val2 = val.replace(/\s+/g, '');
		val2 = val2.replace(/<br>/g, '');
		
		val = val.replace(/<br>/g, '[br]');		
		
		var media = $('#postbox_media_val_' + type + '').text();
		
		if(val2 == "")
			val = val2;
		//alert(val);
		
		if(val2 == "" && media == "") {//alert(val+';'+media);
			$('#postbox_err_msg_' + type + '').text('Its empty!');
			return;
		}
		if(val.length > 400) {
			$('#postbox_err_msg_' + type + '').text('Too long! 400 characters only.');
			return;
		}
		$('#postbox_err_msg_' + type + '').text('');
		
	} else {
		var val = $('#post_box_' + type + '').val();
		
		var media = "";
		if(val == "") {
			$('#postbox_err_msg_' + type + '').text('Its empty!');
			return;
		}
		if(val.length > 400) {
			$('#postbox_err_msg_' + type + '').text('Too long! 400 characters only.');
			return;
		}
		$('#postbox_err_msg_' + type + '').text('');
	}

/*
	alert(user);
	alert(val);
	alert(postas);
	alert(type);
	alert(media);
*/
	$(ele).attr('disabled', true).css('opacity','0.5').val("Saving");
	var postas = $('#postbox_postas_' + type + '').val();
	// the parameter type also shows if it is a group post or a whatsup post
	$.post(
		"php/ajax/postbox_submit.php",
		{user: user, val : val, postas: postas, type: type, media: media},
		function(msg) {
	
			$(ele).attr('disabled', false).css('opacity','0.8').val("Post");
			$('#post_box_' + type + '').html("");

			if(temp1[0] != "pms") {
				var temp = new Array();
				temp = msg.split("_");
				if(temp[0] == "id")
					var postid = temp[1];
				else
					show_msg('<span class="submit_postbox_msg">'+msg+'</span>', "perm");
	
				//clearning up the postbox
				$('#postbox_length_' + type + '').text("400 characters left");				
				post_insert_media("", "remove", type);
					
				// inidiate the subscription function asynchronously
				if(temp[0] == "id")
					init_subscription(postid, type);
					
				} else {
					type_stat(type, user);
					
					var temp = new Array();
					temp = msg.split("_");
					if(temp[0] != "id")
						{ show_msg('<span class="submit_postbox_err">'+msg+'</span>', "perm"); return; }
					
					//init_subscription(temp[1]+"_"+temp[2],"pms");	
			 //alert(msg);
				//init_pms(user,type);
				// this should happen automatically as i am polling
			}
		});
}

function postbox_changed(ele, typeb) {

	var val = $(ele).text();
	var len = val.length;
	if(len > 400) {
		$('#postbox_length_' + typeb + '').text('oops!');
	} else
		$('#postbox_length_' + typeb + '').text("" + (400 - len) + " characters left");

}
function postbox_changed1(event, id)
{	
	if (event.keyCode == 13 && event.shiftKey) {
       //event.stopPropagation();
	}
	else if(event.keyCode == 17)
	{
		event.stopPropagation();
		$('#pb_'+id+' select').find('option').attr('selected','');
		
		$('#pb_'+id+' select').find('option').each(function() {
			if($(this).attr('value') != "anonymous")
				$(this).attr('selected', 'selected');
		});
	}
	else if(event.keyCode == 13)// submit post	
	{	
		event.stopPropagation();
		$('#pb_'+id).find('input[type=submit]').click();
		$('#post_box_' + id + '').html("");
	} 
	
}

function postbox_changed2(event, id)
{	
	if(event.keyCode == 17)
	{
	
	$('#pb_'+id+' select').find('option').attr('selected','');

	$('#pb_'+id+' select').find('option').each(function() {	
			if($(this).attr('value') == "anonymous")
				$(this).attr('selected', "selected");			
		});
	}
}


function del_post(id, ele, type, del_type) {
	//alert(id);
	if(type == "init") {
		//var html = $(ele).parent().html();
		var html1 = '<span>Are you sure? <span class="a" onclick=\'del_post(' + id + ',this, "yes","' + del_type + '")\'>yes</span>	<span class="a" onclick=\'del_post(' + id + ',this, "no","' + del_type + '")\'>no</span></span>';
		$(ele).parent().html(html1);
	} else if(type == "no")
		$(ele).parent().parent().html('<span class="a" onclick=\'del_post(' + id + ',this,"init","' + del_type + '")\'>delete</span>');
	else if(type == "yes") {
		show_msg('<span class="del_postbox_msg">deleting</span>', "perm");
		$.ajax({
			type : "POST",
			url : "php/ajax/del_post.php",
			data : "id="+id+"&del_type="+del_type,
			success : function(msg) {
				//alert("back");
				if(msg != "")
					alert("Something went wrong: " + msg);
				
				//hiding posts and comments 
				if(del_type == "post")
				$('#stream_post_'+id+'').slideUp(); 
				else $('#comment_'+id+'').slideUp();
				
				show_msg("del_postbox_msg", "hide");
				//init_stream();
			}
		});
	} else
		show_msg('<span class"del_post_msg">something went wrong</span>', "alert");
}


function show_fhelp(ele, action) {
	if(action == "show") {
		$('div#fhelp').slideDown();
		$(ele).replaceWith('<span class="formatting_help a" style="color:#555" onclick=\'show_fhelp(this,"hide")\'>hide</span>');
	} else if(action == "hide") {
		$('div#fhelp').slideUp();
		$(ele).replaceWith('<span class="formatting_help a" style="color:#555" onclick=\'show_fhelp(this,"show")\'>help</span>');
	}
}

function post_insert_media(ele, type, typeb) {
	if(type == "vid" || type == "img") {
		if(type == "vid")
			var text = "youtube";
		else
			var text = "image";

		$('div#postbox_media_' + typeb + '').html('Enter the ' + text + ' url here: <br><form onsubmit="return false;"><input type="text" size="30"/>&nbsp;<span class="button"   onclick=\'post_insert_media(this, "' + type + '_submit","' + typeb + '")\'/ >attach</span>&nbsp;<span class="a" onclick=\'post_insert_media(this, "revert","' + typeb + '")\'>cancel</span></form>');
	}
	/* else if(type =="img")
	 {
	 $('div#postbox_media').html('<span class="a" onclick=\'post_insert_media(this,"img_url")\'>Image from URL</span> | <span class="a" onclick=\'post_insert_media(this,"img_upload")\'>upload from computer</span>');
	 }
	 else if(type == "img_url")
	 {
	 var text = "img";
	 $('div#postbox_media').html('Enter the '+text+' url here: <br><form onsubmit="return false;"><input type="text" size="30"/>&nbsp;<span class="a button"   onclick=\'post_insert_media(this, "img_submit")\'/ >attach</span>&nbsp;<span class="a" onclick=\'post_insert_media(this, "revert")\'>cancel</span></form>');
	 }
	 else if(type == "img_upload")
	 {
	 var text = "img";
	 $('div#postbox_media').html('<form onsubmit="return false;"><input type="file" />&nbsp;<span class="button"   onclick=\'post_insert_media(this, "img_submit_upload")\'/ >upload</span>&nbsp;<span class="a" onclick=\'post_insert_media(this, "revert")\'>cancel</span></form>');
	 }
	 */
	else if(type == "revert") {
		// one parent for <form>
		$('#postbox_media_' + typeb + '').html('<span class="a" onclick=\'post_insert_media(this,"img","' + typeb + '")\'>Attach Image</span> &nbsp;  <span class="a" onclick=\'post_insert_media(this,"vid","' + typeb + '")\'>Attach Video</span>');
	} else if(type == "remove") {
		$('#postbox_media_' + typeb + '').html('<span class="a" onclick=\'post_insert_media(this,"img","' + typeb + '")\'>Attach Image</span> &nbsp;  <span class="a" onclick=\'post_insert_media(this,"vid","' + typeb + '")\'>Attach Video</span>');
		$('#postbox_media_val_' + typeb + '').text("");
	} else {
		if(type == "img_submit") {
			$(ele).text("checking");
			var val = $('#postbox_media_' + typeb + '').find('input[type=text]').val();
			if(val == "") {
				$('#postbox_err_msg_' + typeb + '').text("invalid image url");
				$(ele).text("attach");
				return;
			}

			//checking the image url using jquery
			$("<img>", {
				src : val,
				error : function() {// invaliid image;  take action
					$('#postbox_err_msg_' + typeb + '').text("invalid image url");
					$(ele).text("insert");
				},
				load : function() {// image is valid proceed to saving the url
					$.post(
						"php/ajax/post/attach_media.php",
						{ val:  val , type: "img", typeb: typeb},
						function(msg) {
							$('#postbox_media_' + typeb + '').html(msg);
							$('#postbox_media_val_' + typeb + '').text('img_' + val);
						}
					);
				}
			});
		}
		/* else if(type == "img_submit_upload")
		 {
		 $(ele).text("checking");
		 var val =  $('div#postbox_media').find('input[type=file]').val();
		 if(val == "") {$('span#postbox_err_msg').text("you haven't selected any file"); $(ele).text("attach"); return;}

		 $('span#postbox_err_msg').text("uploading..");
		 var res = post_img_upload(val);
		 //if(res == "not")
		 //	$('span#postbox_err_msg').text("it does seem to be an image");
		 //else
		 $('span#postbox_err_msg').text(res);

		 }*/
		else if(type == "vid_submit") {
			var val = $('#postbox_media_' + typeb + '').find('input[type=text]').val();
			if(val.split('v=').length == 1) {
				$('#postbox_err_msg_' + typeb + '').text("invalid video url");
				return;
			}

			var video_id = val.split('v=')[1];
			var ampersandPosition = video_id.indexOf('&');
			if(ampersandPosition != -1) {
				video_id = video_id.substring(0, ampersandPosition);
			}

			// valid video proceed to save it
			$.post(
				"php/ajax/post/attach_media.php",
				{val: video_id, type : "vid", typeb: typeb},
				function(msg) {
					$(ele).parent().parent().html(msg);
					$('#postbox_media_val_' + typeb + '').text('vid_' + video_id);
				}
			);

		}
	}
}

///////////////////////////////////////////////////////// group request  ////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function add_gp_request(gpid, fbid, ele, type) {
	$(ele).css('disabled', true);
	$(ele).val('requesting');

	$.ajax({
		type : "POST",
		url : "php/ajax/add_gp_request.php",
		data : "gpid=" + gpid + "&fbid=" + fbid + "&type=" + type,
		success : function(msg) {
			var temp = new Array();
			temp = msg.split("_");
			if(temp[0] != "id")			
				{ show_msg('<span class="add_gp_request_msg">Something went wrong: ' + msg+'</span>', "perm"); return; }
			
				var requestid = temp[1]+"_"+temp[2];  
				init_subscription(requestid, "request","false");
				window.location.reload();
		}
	});

}

function allow_gp_request(ele, gpid, fbid) {
	$(ele).parent().text('saving..');

	$.ajax({
		type : "POST",
		url : "php/ajax/allow_gp_request.php",
		data : "gpid=" + gpid + "&fbid=" + fbid,
		success : function(msg) {
			var temp = new Array();
			temp = msg.split("_");
			if(temp[0] != "id")			
				{ show_msg('<span class="allow_gp_request_msg">Something went wrong:'+msg+'</span>', "alert"); return; }
				
			else {
				$(ele).parent().text('done!');
				
				var requestid = temp[1]+"_"+temp[2]; 				
				init_subscription(requestid, "request", "false");
				window.location.reload();
			}
		}
	});

}

function make_gp_mod(gpid, fbid, action, ele) {
	if(action == "make") {
		$(ele).text('making').removeClass('a'); $(ele).attr('onclick') == "";
	} else {
		$(ele).text('removing').removeClass('a'); $(ele).attr('onclick') == "";
	}

	$.ajax({
		type : "POST",
		url : "php/ajax/make_gp_mod.php",
		data : "gpid=" + gpid + "&fbid=" + fbid + "&action=" + action,
		success : function(msg) {
			if(msg != "")
				show_msg('<span class="make_gp_mod">Something went wrong: '+msg+'</span>', "alert");
			else
				window.location.reload();
		}
	});

}

function del_gp_user(gpid, fbid, ele) {

	// the ele = "short" thing was designed for lists and removing people in real time without updating the page
	// which is not currently in use
	show_msg('<div class="del_gp_user">deleting..</div>',"perm");
	if(ele!="short")
	{
		$(ele).text('removing').removeClass('a'); 
		$(ele).attr('onclick') == "";
	}
	$.ajax({
		type : "POST",
		url : "php/ajax/del_gp_user.php",
		data : "gpid=" + gpid + "&fbid=" + fbid,
		success : function(msg) {
			show_msg('del_gp_user',"hide");
			if(msg != "")
				show_msg('<span class="del_gp_user">Something went wrong: ' + msg+'</span>', "alert");
			else
			{				
				if(ele != "short")
					window.location.reload();
				else
					{
					show_msg('<div class="del_gp_user">refreshing..</div>',"perm");
					$.ajax({
						type : "POST",
						url : "php/sidebar/group_sidebar.php",
						async : true,
						data : "gpid=" + gpid,
						success : function(data) {	
							$('#group_'+gpid+'_friendsList').html(data);				
							show_msg('del_gp_user',"hide");
						}
					});
					}
			}
		}
	});

}

function del_circle(gpid, user, ele, type) {

	if(type == "question") {
		$(ele).replaceWith('<span> This will delete all the posts in this circle. Are you sure? <span onclick=\'del_circle(' + gpid + ',' + user + ',this,"yes")\' class="a">yes</span> <span onclick=\'del_circle(' + gpid + ',' + user + ',this,"no")\' class="a">no</span></span>');
	} else if(type == "no") {
		$(ele).parent().replaceWith('<span onclick=\'del_circle(' + gpid + ', ' + user + ', this, "question")\' class="a">Delete Circle</span>');
	} else if(type == "yes") {
		$(ele).parent().replaceWith('<span>Deleting</span>');

		$.ajax({
			type : "POST",
			url : "php/ajax/del_circle.php",
			data : "gpid=" + gpid + "&user=" + user,
			success : function(msg) {
				if(msg != "")
					show_msg('<span class="del_circle">Something went wrong: ' + msg+'</span>', "alert");
				else
					window.location = "index.php";
			}
		});
	}
}

function leave_circle(gpid, user, ele, type) {

	if(type == "short")
	{
		if(!confirm("Are you sure you want to leave this group?"))
			return;
		user = $('#loggedin_userid').text();
		
		$.ajax({
				type : "POST",
				url : "php/ajax/leave_circle.php",
				data : "gpid=" + gpid + "&user=" + user,
				success : function(msg) {
					if(msg != "")
						show_msg('<span class="leave_circle">Something went wrong: ' + msg+'</span>', "alert");
					else
						window.location = "index.php";
				}
			});
			
	}
	else
	{
		if(type == "question") {
			$(ele).replaceWith('<span> This will delete all your posts which you have not posted as anonymous. Are you sure? <span onclick=\'leave_circle(' + gpid + ',' + user + ',this,"yes")\' class="a">yes</span> <span onclick=\'leave_circle(' + gpid + ',' + user + ',this,"no")\' class="a">no</span></span>');
		} else if(type == "no") {
			$(ele).parent().replaceWith('<span onclick=\'leave_circle(' + gpid + ', ' + user + ', this, "question")\' class="a">Leave Circle</span>');
		} else if(type == "yes") {
			$(ele).parent().replaceWith('<span>Deleting</span>');

			$.ajax({
				type : "POST",
				url : "php/ajax/leave_circle.php",
				data : "gpid=" + gpid + "&user=" + user,
				success : function(msg) {
					if(msg != "")
						show_msg('<span class="leave_circle">Something went wrong: ' + msg+'</span>', "alert");
					else
						window.location.reload();
				}
			});
		}
	}
}

///////////////////////////////////////////////////////////  GROUP ////////////////////////////////////////////////////////////////

function edit_gp_name(ele, action)// calling with less parameters. the content parameter is not always passed
{
	if(action == "0")// modify form
	{
		$(ele).hide();
		var des = $(ele).parent().find('div.gp_name').text();
		$(ele).parent().find('div.gp_name').hide();
		$(ele).parent().find('div.gp_name_edit').html('<form onsubmit="return false;"><textarea rows="3" cols="40">' + des + '</textarea><br><input type="submit" value="save" onclick="edit_gp_name(this, 1)"><span class="a" onclick=\'edit_gp_des(this, 2)\'>cancel</span></form>');
	} else if(action == "2") {
		$(ele).parent().parent().parent().find('div.gp_name').show();
		$(ele).parent().parent().parent().find('.gp_name_edit_link').show();
		$(ele).parent().parent().parent().find('div.gp_name_edit').html("");
	} else if(action == "1") {
		var val = $(ele).parent().find('textarea').val();
		if(val.length > 500) {
			$(ele).parent().parent().parent().find('div.gp_name_edit').append('Not more than 500 characters');
			return;
		}

		var gpid = $(ele).parent().parent().parent().find('span.gpid').text();
		var par = $(ele).parent().parent().parent().find('div.gp_name_edit');
		par.html("saving..");
		$.post(
			"php/ajax/group/edit_gp.php",
			{gpid: gpid, val: val, type: "name" },
			function(msg) {
				if(msg != "")
					alert(msg);
					par.parent().html('Name: <br><span class="gpid" style="display:none">'+gpid+'</span><div class="gp_name" style="color:#000">'+val+'</div><div class="gp_name_edit"></div><span class="a gp_description_edit_link" onclick="edit_gp_name(this,0)">edit</span>');
			});
	}
}

function post_img_upload(file) {
	// file is from a <input> tag or from Drag'n Drop
	// Is the file an image?
	alert(file);
	if(!file || !file.match(/\.(jpg)|(gif)|(png)|(bmp)$/))
		return "not";

	// It is!
	// Let's build a FormData object
	alert("0");
	var fd = new FormData();
	alert("1");
	fd.append("image", file);
	// Append the file
	alert("2");
	fd.append("key", "e801d24d4c55f42a2c1f5e1d850fa24c");
	// Get your own key: http://api.imgur.com/
	alert("middle");
	// Create the XHR (Cross-Domain XHR FTW!!!)
	var xhr = new XMLHttpRequest();
	xhr.open("POST", "http://api.imgur.com/2/upload.json");
	// Boooom!
	xhr.onload = function() {
		alert("back");
		// Big win!
		// The URL of the image is:
		alert(xhr.responseText);
		alert(JSON.parse(xhr.responseText).upload.links.imgur_page);
		return JSON.parse(xhr.responseText).upload.links.imgur_page;
	}
	// Ok, I don't handle the errors. An exercice for the reader.
	// And now, we send the formdata
	xhr.send(fd);
	alert("sent");
}

function show_frnd_list(filter) {
	$.ajax({
		type : "POST",
		url : "php/ajax/group/frnd_list.php",
		data : "filter=" + filter,
		success : function(msg) {
			$('#frnd_list').html(msg);
			$('#gp_frnd_list_sel').find('input[type=text]').focus();
		}
	});
}

function pb_alter(type)
{
	if($('#pb_'+type+'').is(':visible'))
	{
		//$(ele).text("Create a Post");
		$('#pb_'+type+'').slideUp('fast');
		$('#pb_'+type+'_control').show();
	}
	else if(!$('#pb_'+type+'').is(':visible'))
	{
		//$(ele).text("hide");
		$('#pb_'+type+'').slideDown('fast');
		$('#pb_'+type+'').find('div.pb_postingarea').focus();
		$('#pb_'+type+'_control').hide();
		//alert($('#pb_'+type+'').offset().top);
		//$(window).animate({ scrollTop: $('#pb_'+type+'_control').offset().top+200}, 200);
	}
}

function refresh_left_column(ele)
{
	if(ele != undefined)
		$(ele).attr('onclick','');
	
	// reading the selected id
	var selectedgp_id = "";
	$('#sidebar-div').find('.groupLink').each(function() {
		if($(this).css('font-weight') == "bold")
			selectedgp_id = $(this).attr('id');	
	});
	
	//alert(selectedgp_id);
	
	/*
	$('#left-pane').html('<img src="images/22.gif" style="padding:20px"/>');
	$.ajax({
		type : "POST",
		url : "php/modules/home_feed.php",
		data : "ajax=true",
		success : function(msg) {
			$('#left-pane').html(msg);
		//	$('#right-pane-content').lionbars();
			//add_eventHandlers_leftCol();			
		}
	});
	*/
	
	var user = $('#loggedin_userid').text();
	rotate_image($('#leftColumnRefreshLink').find('img'), "start");
	$('#right-pane-content').css('overflow','hidden');
	$.ajax({
		type : "POST",
		url : "php/sidebar/home_sidebar.php",
		data : "ajax=true&user="+user,
		success : function(msg) {
			rotate_image("", "stop");
			$('#right-pane-content').html(msg);
			$('#right-pane-content').css('overflow','auto');
			add_eventHandlers_leftCol();	
			// restoring the original group that was open
			if(selectedgp_id!="")
				$('#'+selectedgp_id+'').click();
		}
	});
}

function rotate_image(img, type)
{
	if(type == "start")
		image_rotate = setInterval( function() {
		img.rotate(image_rotate_angle);
		image_rotate_angle += 10;
		}, 50);
	else
		{
		//alert("stopped");
		image_rotate_angle = 0;
		clearInterval(image_rotate)		
		}
	
}